package com.example.producer.service;

import com.alibaba.fastjson.JSON;
import com.example.bean.User;
import com.example.producer.aspect.Myannotation;
import com.example.producer.config.RabbitTemplateConfig;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@Service
public class ProducerService {
    @Autowired
    RabbitTemplate rabbitTemplate ;
      @Autowired
      ConnectionFactory connectionFactory;

    //  Server ser = applicationContent.getBean(Server.class);

    public static String getUser() {
        String familyName = "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹喻水云苏潘葛奚范彭郎鲁韦昌马苗凤花方俞任袁柳鲍史唐费岑薛雷贺倪汤滕殷罗毕郝邬安常乐于时傅卞齐康伍余元卜顾孟平"
                + "黄和穆萧尹姚邵湛汪祁毛禹狄米贝明臧计成戴宋茅庞熊纪舒屈项祝董粱杜阮席季麻强贾路娄危江童颜郭梅盛林刁钟徐邱骆高夏蔡田胡凌霍万柯卢莫房缪干解应宗丁宣邓郁单杭洪包诸左石崔吉"
                + "龚程邢滑裴陆荣翁荀羊甄家封芮储靳邴松井富乌焦巴弓牧隗山谷车侯伊宁仇祖武符刘景詹束龙叶幸司韶黎乔苍双闻莘劳逄姬冉宰桂牛寿通边燕冀尚农温庄晏瞿茹习鱼容向古戈终居衡步都耿满弘国文东殴沃曾关红游盖益桓公晋楚闫";
        String boyName = "伟刚勇毅俊峰强军平保东文辉力明永健世广志义兴良海山仁波宁贵福生龙元全国胜学祥才发武新利清飞彬富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪心邦承乐绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德行时泰盛雄琛钧冠策腾楠榕风航弘";
        int i = new Random().nextInt(50);
        User user = new User();
        user.setAge(i);
        user.setName(familyName.substring(i, i + 1) + boyName.substring(i, i + 1));
        return JSON.toJSONString(user);
    }


    public String hello() throws JsonProcessingException {
          rabbitTemplate.convertAndSend("helloQueue",getUser());
        return "hello!";
    }
     //直连会轮询发送给相同routingKey的消费者
    public void directMessage() {

          rabbitTemplate.convertAndSend("myDirectExchange", "mind.direct", getUser());

    }

    //扇形不需要routingkey,发送给绑定的所有交换机
    public void fanoutMessage() {

          rabbitTemplate.convertAndSend("myFanoutExchange", "", getUser());

    }

    @Myannotation(desc = "日志信息", type = "sendMag")
    //开启 firm 和 return
    public void topicMessage() {
        // Mandatory
        // true：RabbitMQ会调用Basic.Return命令将消息返回给生产者
        // false：RabbitMQ会把消息直接丢弃 则不会触发returncallback的回调
        // 配置文件配置
        //rabbitTemplate.setMandatory(true);

        rabbitTemplate = new RabbitTemplateConfig().rabbitTemplate(connectionFactory);

        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {

            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String msg) {
                if (ack) {
                    System.out.println("消息成功发送，存储发送数据 ");
                } else {
                    System.out.println("消息发送失败");
                    System.out.println("错误原因" + msg);
                }
            }
        });
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                System.out.println(returnedMessage.getMessage());
            }
        });

        //消息id设置在请求头里面 用UUID做全局ID
       // Message headers = MessageBuilder.withBody(getUser().getBytes()).setMessageId(String.valueOf(UUID.randomUUID())).setHeader("HEADERS", 666).setContentType(MessageProperties.CONTENT_TYPE_JSON).setContentEncoding("utf-8").build();

        rabbitTemplate.convertAndSend("myTopicExchange", "mine.topic.com", getUser());

    }

    //开启 firm 和 return
    public void liveMessage() {
        // Mandatory
        // true：RabbitMQ会调用Basic.Return命令将消息返回给生产者
        // false：RabbitMQ会把消息直接丢弃 则不会触发returncallback的回调
        // 配置文件配置
        //rabbitTemplate.setMandatory(true);

        rabbitTemplate = new RabbitTemplateConfig().rabbitTemplate(connectionFactory);

        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {

            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String msg) {
                if (ack) {
                    System.out.println("exchange收到消息成功发送，exchange存储发送数据live....");
                } else {
                    System.out.println("exchange未发送消息");
                    System.out.println("错误原因" + msg);
                }
            }
        });
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                System.out.println("回滚================"+returnedMessage.getMessage());
            }
        });
        //消息id设置在请求头里面 用UUID做全局ID
        Message headers = MessageBuilder.withBody(getUser().getBytes()).setMessageId(String.valueOf(UUID.randomUUID())).setHeader("HEADERS", 666).setContentType(MessageProperties.CONTENT_TYPE_JSON).setContentEncoding("utf-8").build();

            rabbitTemplate.convertAndSend("myLiveExchange", "info", headers);


    }
}